The following
char oneD = new char( 'D' ); System.out.println( oneC.length() );
will not even compile.
Line one will not compile because a char
is not an object and so has no constructor.
The next line will not compile because a char
primitive has no methods.
import java.util.Scanner; import java.io.*; class ColumnCheck { public static void main (String[] arg) { final int colNum = 10; int counter = 0; String line = null; Scanner scan = new Scanner( System.in ); while ( scan.hasNext() ) { line = scan.nextLine() ; counter = counter +1; if ( line.length() > colNum && line.charAt( colNum ) != ' ' ) System.out.println( counter + ":\t" + line ); } } }
Here is a program that checks that every line of a text file has a space character in column 10. This might be used to verify the correct formatting of columnar data or of assembly language source programs.
The program is used with redirection (see Chapter 21):
C:\>javac ColumnCheck.java C:\>java ColumnCheck < datafile.txt
If you skipped the chapter on redirection, all you need to know is that
when the program is running the nextLine()
method reads one line from the file.
An improved program might ask the user for several column numbers to check.
Will the program crash if a line has fewer than 10 characters? Inspect the statement
if ( line.length() > colNum && line.charAt( colNum ) != ' ' ) System.out.println( counter + ":\t" + line );
How is the short-circuit nature of && used here?